import MannageService.Manage;
import MannageService.ManageDaoImp;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import java.io.IOException;

@WebServlet(name="MLoginServlet",value = "/MLoginServlet")
public class MLoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String submitButton = req.getParameter("submitButton");
        String registerButton = req.getParameter("registerButton");
        String error="  ";

        if (submitButton != null) {
            // 用户按下了提交按钮
            // 执行提交按钮的逻辑

            //UserDaoImp um = new UserDaoImp();
            ManageDaoImp m=new ManageDaoImp();
            try {
                //User u2 = um.finduser(username);
                Manage manage=m.finduser(username);
                System.out.println(manage.getMname());
                System.out.println(manage.getPassword());

                if (manage.getMname().equals(username) && manage.getPassword().equals(password)) {
                    HttpSession session = req.getSession(true);
                    session.setMaxInactiveInterval(60 * 60);

                    session.setAttribute("manage", manage);
//
//                    Cookie cookie = new Cookie("JSESSIONID", session.getId());
//
//                    cookie.setMaxAge(60 * 60);

//                    resp.addCookie(cookie);
                    // resp.sendRedirect("IndexServlet");
                    System.out.println("222");
                    req.getRequestDispatcher("merchantSite.jsp").forward(req, resp);
                } else {
//                resp.sendRedirect("UserLogin.jsp");
//                System.out.println("111");

                    error = "用户名或密码错误 !  ";
                    req.setAttribute("error", error);

                    // req.getRequestDispatcher("UserLogin.jsp").forward(req,resp);
                    req.getRequestDispatcher("ManageLogin.jsp").forward(req, resp);
                }

            } catch (Exception e) {
                e.printStackTrace();
                // 可以在这里设置一个默认的错误信息，例如：
                error = "查无此管理员！";
                req.setAttribute("error", error);

                // req.getRequestDispatcher("UserLogin.jsp").forward(req,resp);
                req.getRequestDispatcher("ManageLogin.jsp").forward(req, resp);
            }

        }
        else if (registerButton != null) {
            // 用户按下了注册按钮
            // 执行注册按钮的逻辑
            resp.sendRedirect("MRegister.jsp");
        }




    }
}
